package com.example.mybatis.Controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.mybatis.Pojo.TallyBook;
import com.example.mybatis.Pojo.TallyBook1;
import com.example.mybatis.Service.TallyBook1Service;
import com.example.mybatis.Service.TallyBookService;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

@CrossOrigin(origins = "http://localhost:8081")
@RestController
public class TallyBookController {

    @Autowired
    private TallyBookService tallyBookService;

    @Autowired
    private TallyBook1Service tallyBook1Service;

    //图书信息爬取
    @RequestMapping("/library")
    public String library(@RequestBody Map<String, String> data) throws InterruptedException, JSONException {
        String username = data.get("username");
        String password = data.get("password");
        //通过username删除原有数据库，做更新操作
        tallyBook1Service.remove(new QueryWrapper<TallyBook1>().eq("username", username));
        tallyBookService.remove(new QueryWrapper<TallyBook>().eq("username", username));
        //加载驱动
        System.setProperty("webdriver.chrome.driver", "D:\\a\\chromedriver.exe");
        ChromeOptions chromeOptions = new ChromeOptions();
        //解决打开chrome浏览器data;,异常
        chromeOptions.addArguments("--remote-allow-origins=*");
        // 打开chrome浏览器
        WebDriver driver = new ChromeDriver(chromeOptions);
        driver.manage().window().maximize();
        // 进入石河子大学图书馆登录网址
        driver.get("http://authserver.shzu.edu.cn/authserver/login?service=http%3A%2F%2Ftyrzfw.chaoxing.com%2Flogin_auth%2Fcas%2Fshzu%2Findex");
        Thread.sleep(1000);
        //输入学号，密码
        driver.findElement(By.id("username")).sendKeys(username);
        driver.findElement(By.id("password")).sendKeys(password);
        driver.findElement(By.tagName("button")).click();
        //个人空间
        driver.get("https://findshzu.libsp.com/#/personalCenter");
        Thread.sleep(1000);
        driver.get("https://findshzu.libsp.com/#/personalCenter");
        Thread.sleep(2000);

        driver.findElement(By.xpath("//*[@id=\"app\"]/div/div/div[2]/div/div/div/div/div/div[1]/div[5]")).click();
        Thread.sleep(2000);
        //对当前借阅信息进行爬取
        List<WebElement> books = driver.findElements(By.xpath("//*[@id=\"app\"]/div/div/div[2]/div/div/div/div/div/div[2]/div/div/div[2]/div[1]/div[2]/div[1]/div/div/div/div/div/div/table/tbody/tr"));
        if (books.isEmpty()) {
            System.out.println("没有获取到数据行");
        }
        JSONArray rowsArray = new JSONArray();

        for (WebElement row : books) {
            JSONObject rowObject = new JSONObject();
            List<WebElement> cells = row.findElements(By.tagName("td"));
            for (int i = 0; i < cells.size(); i++) {
                String text = cells.get(i).getText();
                rowObject.put("cell" + i, text);

            }
            rowsArray.put(rowObject);
        }
        //对当前借阅信息进行存储
        for (int i = 0; i < rowsArray.length(); i++) {
            JSONObject jsonObject = rowsArray.getJSONObject(i);
            TallyBook tallyBook = new TallyBook();
            tallyBook.setUsername(username);
            tallyBook.setId(jsonObject.getInt("cell1"));
            tallyBook.setSm(jsonObject.getString("cell2"));
            tallyBook.setJyrz(jsonObject.getString("cell6"));
            tallyBook.setYhrq(jsonObject.getString("cell7"));
            tallyBook.setGcd(jsonObject.getString("cell8"));
            tallyBookService.save(tallyBook);
        }
        //对历史借阅信息进行爬取
        driver.findElement(By.xpath("//*[@id=\"app\"]/div/div/div[2]/div/div/div/div/div/div[2]/div/div/div[1]/div/div/div/div/div[3]")).click();
        Thread.sleep(2000);
        //对当前借阅信息进行爬取
        List<WebElement> books1 = driver.findElements(By.xpath("//*[@id=\"app\"]/div/div/div[2]/div/div/div/div/div/div[2]/div/div/div[2]/div[2]/div[2]/div[1]/div/div/div/div/div/div/table/tbody/tr"));
        if (books1.isEmpty()) {
            System.out.println("没有获取到数据行");
        }
        JSONArray rowsArray1 = new JSONArray();

        for (WebElement row : books1) {
            JSONObject rowObject = new JSONObject();
            List<WebElement> cells = row.findElements(By.tagName("td"));
            for (int i = 0; i < cells.size(); i++) {
                String text = cells.get(i).getText();
                rowObject.put("cel" + i, text);
            }
            rowsArray1.put(rowObject);
        }
        //存储数据库
        for (int i = 0; i < rowsArray1.length(); i++) {
            JSONObject jsonObject = rowsArray1.getJSONObject(i);
            TallyBook1 tallyBook1 = new TallyBook1();
            tallyBook1.setUsername(username);
            tallyBook1.setId(jsonObject.getInt("cel0"));
            tallyBook1.setSm(jsonObject.getString("cel1"));
            tallyBook1.setJyrz(jsonObject.getString("cel4"));
            tallyBook1.setYhrq(jsonObject.getString("cel6"));
            tallyBook1.setGcd(jsonObject.getString("cel7"));
            tallyBook1Service.save(tallyBook1);
        }

        return "success";
    }

    //从数据库拿对应username的当前图书借阅数据
    @ResponseBody
    @GetMapping("/tallyBookImpl/{username}")
    public List<TallyBook> getTallyBookListByUsername(@PathVariable String username) {
        return tallyBookService.getTallyBookListByUsername(username);
    }

    //从数据库拿对应username的历史图书借阅数据
    @ResponseBody
    @GetMapping("/tallyBook1Impl/{username}")
    public List<TallyBook1> getTallyBook1ListByUsername(@PathVariable String username) {
        return tallyBook1Service.getTallyBook1ListByUsername(username);
    }

}
